import os
import pandas as pd
import random
import numpy as np
import time
import matplotlib.pyplot as plt

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 设置中文字体
chinese_font = FontProperties(fname='C:/Windows/Fonts/simhei.ttf')  # 黑体 (SimHei)

# 定义路径
base_path = "seedwords_agencywords/agency_words"  # 假设文件夹结构保持不变

# 获取所有种子关键词的文件列表
seedwords_files = [f for f in os.listdir(base_path) if f.startswith("seedword_") and f.endswith(".txt")]

# 初始化存储竞争关键词的字典
competing_keywords = {}

# 第一步：读取每个种子关键词的文件并提取前5个竞争关键词
for seed_file in seedwords_files:
    seed_name = seed_file.replace("seedword_", "").replace(".txt", "")  # 提取种子关键词名称
    file_path = os.path.join(base_path, seed_file)

    # 读取文件内容并提取前5个中介关键词
    with open(file_path, 'r', encoding='utf-8') as f:
        keywords = []
        for line in f:
            if "中介关键字：" in line:
                keyword = line.split("中介关键字：")[1].split("||")[0].strip()  # 提取中介关键词部分
                keywords.append(keyword)
            if len(keywords) >= 5:
                break  # 只提取前5个关键词
        competing_keywords[seed_name] = keywords

# 第二步：定义Compkey算法计算竞争程度
def calculate_competition_degree(comp_keywords):
    competition_scores = {}

    for keyword in comp_keywords:
        search_volume = random.randint(1000, 100000)  # 模拟搜索量
        ad_competition = random.uniform(0.1, 1.0)  # 模拟广告竞争程度（0-1尺度）
        relevance_score = random.uniform(0.1, 1.0)  # 模拟相关性（0-1尺度）

        # Compkey公式（示例：search_volume * ad_competition * relevance_score）
        competition_degree = search_volume * ad_competition * relevance_score
        competition_scores[keyword] = competition_degree

    return competition_scores

# 第三步：计算所有竞争关键词的竞争程度
all_competition_scores = []

for seed, comp_keywords in competing_keywords.items():
    scores = calculate_competition_degree(comp_keywords)
    for keyword, competition_degree in scores.items():
        all_competition_scores.append({
            '种子关键词': seed,
            '竞争关键词': keyword,
            '竞争程度': competition_degree
        })

# 第四步：将所有结果存储在一个DataFrame中并排序
all_results_df = pd.DataFrame(all_competition_scores)
all_results_df = all_results_df.sort_values(by=['种子关键词', '竞争程度'], ascending=[True, False]).reset_index(drop=True)

# 第五步：将结果保存为简洁格式的CSV文件
all_results_df[['种子关键词', '竞争关键词', '竞争程度']].to_csv("competition_results.csv", index=False, encoding='utf-8-sig')
print("所有竞争结果已计算并存入'competition_results.csv'。")

# 第六步：竞争性感知问卷设计与评估
def design_competition_survey():
    questions = [
        "1. 您认为该关键词的市场竞争程度如何？（1-10分）",
        "2. 您认为该关键词的广告投放压力如何？（1-10分）",
        "3. 您认为该关键词的搜索热度如何？（1-10分）",
    ]
    print("\n".join(questions))
    return questions

# 示例问卷生成
design_competition_survey()

# 模拟问卷调查数据
def collect_survey_data(num_responses=50):
    survey_data = []
    for _ in range(num_responses):
        response = {
            "竞争关键词": random.choice(list(competing_keywords.keys())),
            "市场竞争程度": random.randint(1, 5),
            "广告投放压力": random.randint(1, 5),
            "搜索热度": random.randint(1, 5),
        }
        survey_data.append(response)
    return pd.DataFrame(survey_data)

survey_df = collect_survey_data()
survey_df.to_csv("survey_results.csv", index=False, encoding='utf-8-sig')
print("问卷调查数据已保存为'survey_results.csv'。")

# 第七步：统计分析竞争性感知得分
survey_df['感知竞争性得分'] = survey_df[['市场竞争程度', '广告投放压力', '搜索热度']].mean(axis=1)
survey_summary = survey_df.groupby('竞争关键词')['感知竞争性得分'].mean().reset_index()
survey_summary = survey_summary.sort_values(by='感知竞争性得分', ascending=False)
print("感知竞争性得分统计如下：")
print(survey_summary)

# 第八步：算法时间效率分析
def analyze_time_efficiency():
    query_lengths = [10, 100, 5000, 10000, 100000]  # 不同查询日志长度
    times = []

    for length in query_lengths:
        test_queries = [f"测试查询_{i}" for i in range(length)]

        start_time = time.time()
        calculate_competition_degree(test_queries)
        end_time = time.time()

        times.append(end_time - start_time)

    return query_lengths, times

# 绘制时间效率分析图
def plot_time_efficiency():
    lengths, times = analyze_time_efficiency()
    plt.figure(figsize=(10, 6))
    plt.plot(lengths, times, marker='o')
    plt.title("算法时间效率分析", fontproperties=chinese_font)
    plt.xlabel("查询日志长度", fontproperties=chinese_font)
    plt.ylabel("运行时间（秒）", fontproperties=chinese_font)
    plt.grid(True)
    plt.savefig("time_efficiency_analysis.png")
    plt.show()

plot_time_efficiency()
